package com.szxy.common.redis.service.impl;

import com.szxy.common.redis.service.UserService;
import com.szxy.pojo.TbUser;
import com.szxy.utils.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @Auther:zwer
 * @Date:2019/9/12 15:59
 * @Description:com.szxy.common.redis.service.impl.impl
 * @Version:1.0
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Value("${USER_SESSION_REDIS_KEY}")
    private String USER_SESSION_REDIS_KEY;

    @Override
    public void insertUserToken(TbUser tbUser, String token) {
        // 设置密码为空，出于安全考虑
        tbUser.setPassword("");
        // 失效时间设置为一天
        this.redisTemplate.opsForValue()
                .set(this.USER_SESSION_REDIS_KEY+":"+token,tbUser, 1 , TimeUnit.DAYS);
    }

    @Override
    public TbUser getUserToken(String token) {
        return (TbUser) this.redisTemplate .opsForValue().get(this.USER_SESSION_REDIS_KEY+":"+token);
    }

    @Override
    public void removeUserToken(String token) {
        this.redisTemplate.delete(this.USER_SESSION_REDIS_KEY+":"+token);
    }

    @Override
    public TbUser checkUserToken(String userToken) {
        return (TbUser) this.redisTemplate.opsForValue().get(this.USER_SESSION_REDIS_KEY+":"+userToken);
    }
}
